<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频播放 - 弹幕视频网站</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script type="importmap">
    {
      "imports": {
        "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
      }
    }
    </script>
    <style>
        .video-container {
            position: relative;
            width: 100%;
            max-width: 100%;
            background: #000;
        }
        .danmaku-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 10;
            overflow: hidden;
        }
        .danmaku {
            position: absolute;
            white-space: nowrap;
            font-weight: bold;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
            font-size: 24px;
            pointer-events: none;
        }
        @keyframes danmaku-move {
            from { transform: translateX(0); }
            to { transform: translateX(-100vw); }
        }
        .danmaku-controls {
            margin-top: 1rem;
        }
        .comment-section {
            margin-top: 2rem;
        }
    </style>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container">
                <a class="navbar-brand" href="/">弹幕视频网站</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link" href="/">首页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/upload.html">上传视频</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <div class="container mt-4">
            <div v-if="loading" class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">正在加载视频...</p>
            </div>

            <div v-else-if="error" class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i>
                {{ error }}
            </div>

            <div v-else>
                <h3 v-if="videoInfo">{{ videoInfo.title }}</h3>
                
                <div class="video-container">
                    <video ref="videoPlayer" 
                           :src="videoSrc"
                           @loadedmetadata="onVideoLoaded"
                           @timeupdate="onTimeUpdate"
                           @seeking="onSeeking"
                           @play="onPlay"
                           @pause="onPause"
                           controls>
                    </video>
                    <div ref="danmakuContainer" class="danmaku-container"></div>
                </div>

                <div class="danmaku-controls">
                    <div class="input-group">
                        <input type="text" 
                               class="form-control" 
                               v-model="danmakuInput"
                               placeholder="输入你的弹幕...">
                        <input type="color" 
                               class="form-control form-control-color" 
                               v-model="danmakuColor">
                        <select class="form-select" v-model="danmakuPosition">
                            <option value="scroll">滚动</option>
                            <option value="top">顶部</option>
                            <option value="bottom">底部</option>
                        </select>
                        <button class="btn btn-primary" @click="sendDanmaku">发送弹幕</button>
                    </div>
                </div>

                <div class="comment-section">
                    <h3>评论区</h3>
                    <div class="mb-3">
                        <textarea class="form-control" 
                                  v-model="commentInput"
                                  :disabled="!isAuthenticated"
                                  :placeholder="isAuthenticated ? '写下你的评论...' : '请先登录后再发表评论'"
                                  rows="3"></textarea>
                        <button class="btn btn-primary mt-2" 
                                :disabled="!isAuthenticated || !commentInput.trim()"
                                @click="sendComment">发表评论</button>
                    </div>
                    <div id="commentList">
                        <div v-if="loadingComments" class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading comments...</span>
                            </div>
                        </div>
                        <div v-else-if="comments.length === 0" class="alert alert-info">
                            暂无评论，来发表第一条评论吧！
                        </div>
                        <div v-else>
                            <div v-for="comment in comments" :key="comment.id" class="card mb-2">
                                <div class="card-body">
                                    <p class="card-text">{{ comment.content || '' }}</p>
                                    <p class="card-text">
                                        <small class="text-muted">
                                            Posted by {{ comment.commenter || 'Anonymous' }} at {{ formatDate(comment.createdAt) }}
                                        </small>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script type="module">
        import { createApp, ref, computed, onMounted, nextTick } from 'vue';
        import { authState, checkAuthStatus, showToast } from '/js/auth.js';

        // DanmakuManager class
        class DanmakuManager {
            constructor(container, width, height) {
                this.container = container;
                this.width = width;
                this.height = height;
                this.lanes = new Array(Math.floor(height / 30)).fill(null);
                this.activeDanmaku = new Set();
            }

            addDanmaku(text, color, position) {
                const danmaku = document.createElement('div');
                danmaku.className = 'danmaku';
                danmaku.textContent = text;
                danmaku.style.color = color;
                
                this.container.appendChild(danmaku);
                
                if (position === 'scroll') {
                    const lane = this.findFreeLane();
                    if (lane === -1) return;
                    
                    danmaku.style.top = `${lane * 30}px`;
                    danmaku.style.left = `${this.width}px`;
                    danmaku.style.animation = `danmaku-move 8s linear`;
                    danmaku.style.animationPlayState = 'running';
                    
                    this.activeDanmaku.add(danmaku);
                    setTimeout(() => {
                        if (this.container.contains(danmaku)) {
                            this.container.removeChild(danmaku);
                        }
                        this.activeDanmaku.delete(danmaku);
                    }, 8000);
                } else {
                    danmaku.style[position] = '10%';
                    danmaku.style.left = '50%';
                    danmaku.style.transform = 'translateX(-50%)';
                    
                    setTimeout(() => {
                        if (this.container.contains(danmaku)) {
                            this.container.removeChild(danmaku);
                        }
                    }, 5000);
                }
            }

            findFreeLane() {
                return this.lanes.findIndex(lane => !lane);
            }

            pauseAll() {
                this.container.querySelectorAll('.danmaku').forEach(d => {
                    d.style.animationPlayState = 'paused';
                });
            }

            resumeAll() {
                this.container.querySelectorAll('.danmaku').forEach(d => {
                    d.style.animationPlayState = 'running';
                });
            }

            clear() {
                this.container.innerHTML = '';
                this.activeDanmaku.clear();
            }
        }

        createApp({
            setup() {
                const loading = ref(true);
                const error = ref('');
                const videoInfo = ref(null);
                const videoSrc = ref('');
                const videoPlayer = ref(null);
                const danmakuContainer = ref(null);
                const danmakuManager = ref(null);
                
                const danmakuInput = ref('');
                const danmakuColor = ref('#ffffff');
                const danmakuPosition = ref('scroll');
                const danmakuData = ref([]);
                
                const commentInput = ref('');
                const comments = ref([]);
                const loadingComments = ref(false);
                
                let lastPlayedIndex = 0;
                let lastTime = 0;

                // Auth computed properties
                const isAuthenticated = computed(() => authState.isAuthenticated);
                const currentUser = computed(() => authState.currentUser);

                // Get video ID from URL
                const getVideoId = () => {
                    const urlParams = new URLSearchParams(window.location.search);
                    return urlParams.get('id');
                };

                // Load video details
                const loadVideo = async () => {
                    const videoId = getVideoId();
                    if (!videoId) {
                        error.value = '视频ID不存在';
                        loading.value = false;
                        return;
                    }

                    try {
                        const response = await fetch(`/api/videos/${videoId}`);
                        if (!response.ok) {
                            throw new Error('Video not found');
                        }
                        
                        const video = await response.json();
                        if (!video || !video.filePath) {
                            throw new Error('Invalid video data');
                        }
                        
                        videoInfo.value = video;
                        videoSrc.value = `/uploads/${video.filePath}`;
                        document.title = `${video.title || 'Untitled'} - Video Danmaku`;
                        
                        // Load danmaku data
                        await loadDanmaku(videoId);
                        
                    } catch (err) {
                        console.error('Error loading video:', err);
                        error.value = '无法加载视频，请稍后重试';
                    } finally {
                        loading.value = false;
                    }
                };

                // Load danmaku data
                const loadDanmaku = async (videoId) => {
                    try {
                        const response = await fetch(`/api/danmaku/video/${videoId}`);
                        if (!response.ok) {
                            throw new Error('Failed to load danmaku');
                        }
                        
                        const danmakuList = await response.json();
                        if (!Array.isArray(danmakuList)) {
                            console.warn('Danmaku list is not an array:', danmakuList);
                            danmakuData.value = [];
                            return;
                        }
                        
                        // Sort danmakus by timestamp
                        danmakuList.sort((a, b) => a.timestamp - b.timestamp);
                        danmakuData.value = danmakuList;
                        
                    } catch (err) {
                        console.error('Error loading danmaku:', err);
                        danmakuData.value = [];
                    }
                };

                // Load comments
                const loadComments = async () => {
                    const videoId = getVideoId();
                    if (!videoId) return;

                    loadingComments.value = true;
                    try {
                        const response = await fetch(`/api/comments/video/${videoId}`);
                        if (!response.ok) {
                            throw new Error('Failed to load comments');
                        }
                        
                        const commentList = await response.json();
                        comments.value = Array.isArray(commentList) ? commentList : [];
                        
                    } catch (err) {
                        console.error('Error loading comments:', err);
                        comments.value = [];
                    } finally {
                        loadingComments.value = false;
                    }
                };

                // Video event handlers
                const onVideoLoaded = async () => {
                    await nextTick();
                    if (danmakuContainer.value && videoPlayer.value) {
                        danmakuManager.value = new DanmakuManager(
                            danmakuContainer.value,
                            videoPlayer.value.offsetWidth,
                            videoPlayer.value.offsetHeight
                        );
                    }
                };

                const onTimeUpdate = () => {
                    if (!danmakuManager.value || !danmakuData.value.length) return;
                    
                    const currentTime = videoPlayer.value.currentTime;
                    
                    // If seek back, reset danmaku index and clear container
                    if (currentTime < lastTime) {
                        lastPlayedIndex = 0;
                        danmakuManager.value.clear();
                    }
                    lastTime = currentTime;
                    
                    // Play danmakus at the current timestamp
                    while (lastPlayedIndex < danmakuData.value.length && 
                           danmakuData.value[lastPlayedIndex].timestamp <= currentTime) {
                        const danmaku = danmakuData.value[lastPlayedIndex];
                        danmakuManager.value.addDanmaku(
                            danmaku.content,
                            danmaku.color || '#ffffff',
                            danmaku.position || 'scroll'
                        );
                        lastPlayedIndex++;
                    }
                };

                const onSeeking = () => {
                    if (!danmakuData.value.length) return;
                    
                    const currentTime = videoPlayer.value.currentTime;
                    lastPlayedIndex = danmakuData.value.findIndex(d => d.timestamp > currentTime);
                    if (lastPlayedIndex === -1) {
                        lastPlayedIndex = danmakuData.value.length;
                    }
                };

                const onPlay = () => {
                    if (danmakuManager.value) {
                        danmakuManager.value.resumeAll();
                    }
                };

                const onPause = () => {
                    if (danmakuManager.value) {
                        danmakuManager.value.pauseAll();
                    }
                };

                // Send danmaku
                const sendDanmaku = async () => {
                    const content = danmakuInput.value.trim();
                    if (!content) return;

                    const videoId = getVideoId();
                    if (!videoId) return;

                    const data = new URLSearchParams({
                        videoId: videoId,
                        content: content,
                        timestamp: videoPlayer.value.currentTime,
                        position: danmakuPosition.value,
                        color: danmakuColor.value,
                        size: 24
                    });

                    try {
                        const response = await fetch('/api/danmaku', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            credentials: 'include',
                            body: data
                        });
                        
                        if (!response.ok) {
                            throw new Error(`发送失败: ${response.status}`);
                        }
                        
                        const result = await response.json();
                        danmakuInput.value = '';
                        
                        // Immediately show the danmaku
                        if (danmakuManager.value) {
                            danmakuManager.value.addDanmaku(content, danmakuColor.value, danmakuPosition.value);
                        }
                        
                        console.log('弹幕发送成功:', result);
                        
                    } catch (err) {
                        console.error('发送弹幕失败:', err);
                        showToast('发送弹幕失败，请稍后重试', 'error');
                    }
                };

                // Send comment
                const sendComment = async () => {
                    const content = commentInput.value.trim();
                    if (!content) return;

                    // Check login status
                    if (!isAuthenticated.value) {
                        showToast('请先登录后再发表评论', 'error');
                        window.location.href = '/login.html?redirect=' + encodeURIComponent(window.location.href);
                        return;
                    }

                    const videoId = getVideoId();
                    if (!videoId) return;

                    const data = new URLSearchParams({
                        videoId: videoId,
                        content: content
                    });

                    try {
                        const response = await fetch('/api/comments', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            credentials: 'include',
                            body: data
                        });
                        
                        if (!response.ok) {
                            if (response.status === 401) {
                                showToast('请先登录后再发表评论', 'error');
                                window.location.href = '/login.html?redirect=' + encodeURIComponent(window.location.href);
                                return;
                            }
                            throw new Error(`发表评论失败: ${response.status}`);
                        }
                        
                        const result = await response.json();
                        commentInput.value = '';
                        await loadComments(); // Reload comments
                        console.log('评论发表成功:', result);
                        
                    } catch (err) {
                        console.error('发表评论失败:', err);
                        showToast('发表评论失败，请稍后重试', 'error');
                    }
                };

                // Utility functions
                const formatDate = (dateString) => {
                    if (!dateString) return '';
                    return new Date(dateString).toLocaleString();
                };

                // Lifecycle
                onMounted(async () => {
                    // Check auth status (but don't require login for viewing)
                    await checkAuthStatus(false);
                    
                    // Load video and comments
                    await loadVideo();
                    await loadComments();
                });

                return {
                    loading,
                    error,
                    videoInfo,
                    videoSrc,
                    videoPlayer,
                    danmakuContainer,
                    danmakuInput,
                    danmakuColor,
                    danmakuPosition,
                    commentInput,
                    comments,
                    loadingComments,
                    isAuthenticated,
                    currentUser,
                    onVideoLoaded,
                    onTimeUpdate,
                    onSeeking,
                    onPlay,
                    onPause,
                    sendDanmaku,
                    sendComment,
                    formatDate
                };
            }
        }).mount('#app');
    </script>
</body>
</html>
